<template>
  <div>
    <!-- 验证码输入框 -->
    <van-cell-group>
      <van-field
        v-model="yzm"
        label="验证码"
        placeholder="请输入验证码"
        autofocus
      >
        <!-- 验证码倒计时 -->
        <template #button>
          <van-button
            size="small"
            :disabled="btnFlag"
            type="primary"
            @click="sendMsg"
            >{{ txt }}</van-button
          >
        </template>
      </van-field>
    </van-cell-group>
    <div class="loginBtn">
      <van-button
        type="danger"
        round
        size="large"
        @click="next"
        :disabled="flag"
        >下一步</van-button
      >
    </div>
  </div>
</template>

<script>
//引入验证码接口 验证验证码接口
import { doSendMsg, doCheckCode } from "../../api/user";
import Vue from "vue";
import { Toast } from "vant";
Vue.use(Toast);
export default {
  data() {
    return {
      yzm: "",
      txt: "发送验证码",
      time: 60,
      btnFlag: false,
    };
  },
  methods: {
    next() {
      //验证验证码
      doCheckCode({ tel: localStorage.getItem("tel"), telcode: this.yzm }).then(
        (res) => {
          console.log(res.data.code);
          switch (res.data.code) {
            case "10007":
              Toast("输入有误，请重新输入");
              break;
            case "200":
              this.$router.push("/register/three");
              break;
            default:
              break;
          }
        }
      );
    },
    sendMsg() {
      //效果上是倒计时
      const timer = setInterval(() => {
        this.time--;
        if (this.time == 0) {
          clearInterval(timer);
          this.btnFlag = false;
          this.txt = "发送验证码";
          this.time = 60;
        } else {
          this.txt = this.time + "s后发送";
          this.btnFlag = true;
        }
      }, 1000);
      //实际上真实发
      setTimeout(() => {
        doSendMsg({ tel: localStorage.getItem("tel") }).then((res) => {
          console.log(res.data.data);
          //发送验证码赋值到输入框验证码
          this.yzm = res.data.data;
        });
      }, 3000);
    },
  },
  computed: {
    flag() {
      if (/^\d{5}$/.test(this.yzm)) {
        return false; //按钮红色可用
      } else {
        return true; //按钮灰色禁用
      }
    },
  },
};
</script>

<style scoped>
.loginBtn {
  width: 90%;
  margin: 20px auto;
}
</style>